<template>
  <div>
                    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
        <el-card>
      <el-alert center title="添加商品信息" type="info" show-icon :closable="false"></el-alert>
            <!-- 步骤条,这里的active绑定的必须是number，从0开始，因此将activeIndex字符串转换为数字 -->
      <el-steps :active="activeIndex-0" align-center :space="200" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性" ></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top" class="demo-ruleForm">
        <el-tabs :before-leave="handleTabRemove" @tab-click="handleTabClick" v-model="activeIndex" tab-position="left">
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
                        <!-- 级联选择器，可选项数据源，键名可通过 Props 属性配置,v-model是选中的选择器的id，必须是个数组 -->
              <el-cascader clearable v-model="addForm.goods_cat" :options="cateList" :props="{ expandTrigger: 'hover',
                value: 'cat_id', label: 'cat_name', children: 'children' }"
                @change="chooseCateChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="(item,id) in manyTableList" :key="id">
               <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox border  v-for="(subItem,subId) in item.attr_vals" :key="subId" :label="subItem"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="(item,id) in onlyTableList" :key="id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :headers="headersObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
                        <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="addGoodBtn" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    <!-- 图片预览效果 -->
    <!--      图片预览-->
      <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
        <img :src="previewPath" class="previewImg">
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
// 导入深拷贝（提交到服务器的goods_cat必须是字符串，但是级联选择器双向绑定了身为数组的goods_cat，
// 因此会出现问题，所以来一个深拷贝解决问题）
import _ from 'lodash'
export default {

  data () {
    return {
      // tab标签选中的
      activeIndex: '',
      // 获取商品分类
      cateList: [],
      // 获取商品列表所有数据
      goodsList: [],
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 商品分类
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 商品的详情描述
        goods_introduce: '',
        attrs: []
      },
      // 添加商品的验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      manyTableList: [],
      onlyTableList: [],
      uploadURL: 'http://47.100.175.102:8888/api/private/v1/upload/',
      // 图片上传的headers请求头（见main中的axios,此组件不经过axios，所以要重新指定）
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览
      previewVisible: false,
      // 图片预览
      previewPath: ''
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    // 级联选择器选中的三级商品分类
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  },
  methods: {
    // 级联选择器商品分类一选择
    // 这里限制级联选择器只能选择三级分类
    chooseCateChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 获取所有商品分类
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error('获取商品分类数据失败')
      } else {
        this.cateList = res.data
        // console.log(this.cateList)
      }
    },
    // tab标签被选中
    async handleTabClick () {
      console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status === 200) {
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          })
          this.manyTableList = res.data
          console.log(this.manyTableList)
        }
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status === 200) {
          res.data.forEach(item => {
          })
          this.onlyTableList = res.data
          console.log(this.onlyTableList)
        }
      }
    },
    // tab标签移除
    handleTabRemove (activeName, oldActiveName) {
      // console.log('即将离开的' + oldActiveName)
      // console.log('即将进入的' + activeName)
      // console.log(this.addForm.goods_cat)
      // // return false
      // 如果此时tab位于第一个标签，并且商品分类没有选择三级分类，则不让跳转到第二个tab标签
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.warning('请选择商品分类')
        return false
      }
    },
    // 上传图片的预览效果
    handlePreview (file) {
      console.log(file)
      // 上传成功之后，服务器会返回一个地址，代表这个图片在服务器端的地址
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 上传图片的移除效果
    handleRemove (file) {
      // console.log(file)
      // 1,首先获取要删除图片的临时路径
      const tmpPath = file.response.data.tmp_path
      // 2, 从pics数组中，找到对应的索引值
      const index = this.addForm.pics.findIndex(item => item.pic === tmpPath)
      // 3,调用数组的splice方法，把图片信息对象从pics数组中移除
      this.addForm.pics.splice(index, 1)
    },
    // 图片一旦成功上传，调用这个钩子函数
    handleSuccess (response) {
      console.log(response)
      // 1,先将图片的pic路径取出来
      const picInfo = { pic: response.data.tmp_path }
      // 2，将图片信息保存到pics数组中
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    },
    // 添加整个商品表单
    add () {
      // 提交的goods_cat需要是以，分割的字符串
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 这里执行深拷贝，form是用来作为字符串提交给服务器的
          const form = _.cloneDeep(this.addForm)
          // 将原先的数组转换成字符串，并且以，分割
          form.goods_cat = form.goods_cat.join(',')
          // 处理动态参数和静态属性
          // 因为之前将动态参数的vals由字符串变成了数组（split），所以这里要变回去
          this.manyTableList.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(' ')
            }
            this.addForm.attrs.push(newInfo)
          })
          this.onlyTableList.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addForm.attrs.push(newInfo)
          })
          form.attrs = this.addForm.attrs
          // console.log(form)
          const { data: res } = await this.$http.post('goods', form)
          console.log(res)
          if (res.meta.status !== 201) {
            this.$message.error('添加失败')
          } else {
            this.$message.success('添加成功')
            this.$router.push('/goods')
          }
        } else {
          return false
        }
      })
    }

  }
}
</script>

<style scoped>
.el-breadcrumb{
  margin-bottom: 15px
}
.el-alert{
  margin-bottom: 15px
}
.el-checkbox{
  margin: 0 10px 0 10px !important
}
.previewImg{
  width: 100%;
}
.addGoodBtn{
  margin-top: 15px
}
</style>
